package cn.tedu.search.controller;

import com.jt.common.pojo.Product;
import com.jt.common.utils.MapperUtil;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequestBuilder;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class CreateIndexController {
    @Autowired
    RestHighLevelClient highLevelClient;

    @Autowired
    RestTemplate restTemplate;

    /**
     * 注入mapper对象，获取商品数据的list
     * 按照新增文档的说明，将所有商品的信息转化为json存储在elasticsearch的集群中
     */
    @RequestMapping("/create")
    public String createIndex(String indexName, String typeName) {
        // 调用微服务获取商品数据
        String url = "http://productservice/product/manage/queryAllProduct";
        List<Product> productList = null;
        try {
            Product[] products = restTemplate.getForObject(url, Product[].class);
            productList = new ArrayList<>();
            for (Product product : products)
                productList.add(product);
        } catch (RestClientException restClientException) {
            restClientException.printStackTrace();
            return "Get products failed";
        }

        IndicesClient indicesClient = highLevelClient.indices();
        try {
            GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
            boolean exists = indicesClient.exists(getIndexRequest, RequestOptions.DEFAULT);
            if (!exists) {
                CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
                createIndexRequest.settings(Settings.builder()
                        .put("index.number_of_shards", 5)   //分片数
                        .put("index.number_of_replicas", 1));//副本数
                createIndexRequest.alias(new Alias(indexName + "_alias"));//设置别名
                createIndexRequest.setTimeout(TimeValue.timeValueMinutes(2));//设置创建索引超时2分钟
                CreateIndexResponse createIndexResponse = indicesClient.create(createIndexRequest, RequestOptions.DEFAULT);
            }

            // TODO 在刚生成index后，会导致无法写入json，必须在index生成之后再次写入
            for (Product product : productList) {
                // 封装成json，client发起请求写入es索引
                // 转化对象为json
                String productJson = MapperUtil.MP.writeValueAsString(product);
                // 调用client的api生成request，将json包装
                BulkRequest bulkRequest = new BulkRequest();
                UpdateRequest updateRequest = new UpdateRequest(indexName, product.getProductId()).doc(productJson, XContentType.JSON);
                bulkRequest.add(updateRequest.upsert());
                highLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            }

            highLevelClient.close();
            return "success";
        } catch (IOException ioException) {
            ioException.printStackTrace();
            return "Create index failed";
        }
    }
}
